#include <stdio.h>
#include <conio.h>
#include <graphics.h>

float height, width;//窗口的大小
float ball_x, ball_y, ball_vy, radius, g;//与小球有关的变量
float rect_left_x, rect_top_y, rect_width, rect_height1, rect_height2;//与方块有关的变量
float rect_vx;//方块移动的速度
int score = 0;//分数

void givenumber()//赋值函数
{
	height = 400;
	width = 600;

	rect_height1 = 125;
	rect_height2 = 125;
	rect_width = 15;
	rect_left_x = width * 3 / 4;
	rect_top_y = height - rect_height1;

	ball_vy = 0;
	g = 0.5;

	ball_x = width / 4;
	radius = 10;
	ball_y = height - radius;

	rect_vx = -3;
}

void draw()//绘图函数
{
	fillrectangle(rect_left_x, height - rect_height1, rect_left_x + rect_width, height);
	fillrectangle(rect_left_x, 0, rect_left_x + rect_width, rect_height2);
	fillcircle(ball_x, ball_y, radius);
}

void Updatenormal()//常规更新
{
	if (ball_y >= height - radius)//使小球落在地面
	{
		ball_vy = 0;
		ball_y = height - radius;
	}

	if (rect_left_x <= 0)//控制得分与方块刷新
	{
		rect_left_x = width;
		rect_height1 = rand() % int(height / 4) + height / 4;
		rect_vx = rand() / float(RAND_MAX) * 4 - 7;
		rect_height2 = height - rect_height1 - 150;//通过下方方块的高计算上方方块
		score++;
	}

	if ((rect_left_x <= ball_x + radius)//失败条件
		&& (rect_left_x + rect_width >= ball_x - radius)
		&& ((height - rect_height1 <= ball_y + radius) || (rect_height2 >= ball_y - radius)))
	{
		Sleep(50);
		score = 0;
	}
}

int main(void)
{
	givenumber();

	initgraph(width, height);

	BeginBatchDraw();
	while (1)
	{
		if (_kbhit())//控制小球起跳
		{
			char input = _getch();
			if (input == ' ')
			{
				ball_vy = -10;
			}
		}

		ball_vy += g;//小球竖直自由落体
		ball_y += ball_vy;
		rect_left_x += rect_vx;//方块移动

		Updatenormal();

		cleardevice();
		draw();

		TCHAR s[20];//显示得分
		swprintf_s(s, _T("%d"), score);
		settextstyle(40, 0, _T("宋体"));
		outtextxy(50, 30, s);

		FlushBatchDraw();
		Sleep(10);
	}

	closegraph();
	return 0;
}